package com.wkck.interceptor;

import com.wkck.constant.JwtClaimsConstant;
import com.wkck.context.BaseContext;
import com.wkck.properties.JwtProperties;
import com.wkck.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 管理端Jwt校验
 */
@Component
@Slf4j
public class JwtTokenAdminInterceptor implements HandlerInterceptor {

    @Autowired
    private JwtProperties jwtProperties;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 拦截到的不是动态方法直接放行
        if(!(handler instanceof HandlerMethod) ) {
            return true;
        }

        String adminToken = request.getHeader(jwtProperties.getAdminTokenName());

        try {
            log.info("开始进行令牌校验: {}", adminToken);
            Claims claims = JwtUtil.parseJWT(jwtProperties.getAdminSecretKey(), adminToken);
            Long empId = Long.valueOf(claims.get(JwtClaimsConstant.EMP_ID).toString());
            log.info("当前管理员Id: {}" ,empId);
            BaseContext.setCurrentId(empId);
            return true;
        } catch (Exception exception) {
            response.setStatus(401);
            log.error("令牌校验失败: {}", adminToken);
            return false;
        }
    }
}
